import { ref } from "vue";
/**
 * 倒计时hooks
 * @param done 倒计时结束触发
 * @param ms 倒计时间隔
 * @param duration 倒计时时间
 * @returns
 */
export const useCountdown = (duration = 60, ms = 1000, done?: () => void) => {
	const lastSendTime = ref(0);
	let timer: NodeJS.Timer | any;
	const start = () => {
		lastSendTime.value = duration;
		if (timer) return;
		timer = setInterval(() => {
			lastSendTime.value--;
			if (lastSendTime.value <= 0) {
				done && done();
				lastSendTime.value = duration;
				clearCountDown();
			}
		}, ms);
	};
	const clearCountDown = () => {
		lastSendTime.value = 0;
		clearInterval(timer);
		timer = undefined;
	};
	const setTime = (time: number) => {
		if (time > 0 && time < 60) {
			lastSendTime.value = time;
		}
	};
	return {
		lastSendTime,
		setTime,
		clearCountDown,
		start
	};
};
